﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using BlueHarvestSnippetGenerator.Snippets.SnippetModel;
using DataContextLayer;

namespace BlueHarvestSnippetGenerator.Snippets.SnippetControl
{
    public class SnippetBuilder
    {

        private const string XmlNamespace = "http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet";
        private readonly CodeSampleInterpreter _codeSampleInterpreter;
        private readonly XDocument _snippetDoc;

        public SnippetBuilder()
        {
            _codeSampleInterpreter = new CodeSampleInterpreter();
            _snippetDoc = XDocument.Load(UserProfile.CurrentSnippet);
        }

        public IEnumerable<Snippet> CreateSnippet()
        {
            
            XNamespace ns = XmlNamespace;

            var test = (_snippetDoc.Descendants(ns + "CodeSnippet").Any());

            var snippets = from s in (test)? _snippetDoc.Descendants(ns + "CodeSnippet")
                                           : _snippetDoc.Descendants("template")
                select new Snippet
                    {
                        Title =(test)? s.Element(ns + "Header").TryGetElementValue(ns, "Title") : s.TryGetElementValue("name"),
                        Description =(test)? s.Element(ns + "Header").TryGetElementValue(ns, "Description") : s.TryGetElementValue("description"),
                        Shortcut =(test)? s.Element(ns + "Header").TryGetElementValue(ns, "Shortcut"):"none",
                        CodeSample =(test)? CreateCodeSample(s.Element(ns + "Snippet"), ns) : s.TryGetElementValue()
                    };

            return snippets;
           
        }

     
        private string CreateCodeSample(XElement element, XNamespace ns)
        {
            var snippetDetail = new SnippetDetail();
            var declarations = from s in element.Descendants(ns + "Literal")
                               select new VariableDeclaration
                               {
                                  Id = s.TryGetElementValue(),
                                  DefaultValue = s.TryGetElementValue("Default"),
                                  FunctionValue = s.TryGetElementValue("Function")
                               };
           
            //takes the code section and splits the variable declarations from the code
            snippetDetail.VariableDeclarations = declarations.ToList();
            snippetDetail.SnippetTemplate = element.TryGetElementValue(ns , "Code");

            return _codeSampleInterpreter.InterpreteSnippetTemplate(snippetDetail);
          
        }
        
    }
}
